package org.biojava.services.das.servlets;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.sql.DataSource;

import org.biojava.dasobert.das.Capabilities;
import org.biojava.dasobert.das.DasSpec;
import org.biojava.dasobert.das2.io.DasSourceWriter;
import org.biojava.dasobert.das2.io.DasSourceWriterImpl;
import org.biojava.dasobert.dasregistry.Das1Source;
import org.biojava.dasobert.dasregistry.DasCoordinateSystem;
import org.biojava.dasobert.dasregistry.DasSource;
import org.biojava.dasobert.dasregistry.DasValidationResult;
import org.biojava.services.das.registry.ConfigBean;
import org.biojava.services.das.registry.DasRegistrySql;
import org.biojava.utils.xml.XMLWriter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import dasregistry.validation.Validator;

/**
 * Servlet implementation class Validate
 */
public class ValidateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private boolean gzipEncoding = true; 
	
	private static String XSL_FILE = "das.xsl";
    /**vla
     * @see HttpServlet#HttpServlet()
     */
    public ValidateServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String cmdPath = request.getPathInfo();
		if (cmdPath == null) {
			cmdPath = "";
		}
		//System.out.println("commandPath " + cmdPath);

		if (cmdPath.endsWith("das.xsl")){
			// return the xsl file
			showXSLFile(response);
			return;
		}

		
		ApplicationContext context = new ClassPathXmlApplicationContext("config_dasregistry.xml");

		DasRegistrySql registry = (DasRegistrySql) context.getBean("registryBean");

//		ConfigBean config = (ConfigBean) context.getBean("configBean");
//		boolean showValidationLog = config.isPrintValidationStatus();
//		
//		DataSource dataSource = registry.getDataSource();
//		//accept post requests and need
//		//System.out.println("spec selecton="+spec+" "+url + " " + testcode + " " + caps +" "+auto_id);
//		String encodingStr = request.getHeader("Accept-Encoding");
//		if (encodingStr != null && gzipEncoding)  {
//			if (encodingStr.indexOf("gzip") != -1) {
//				response = new HttpServletResponseWrapper(response) {
//					GZIPOutputStream gzipOut = null;
//					public PrintWriter getWriter() throws IOException {
//						gzipOut = new GZIPOutputStream(getResponse().getOutputStream());
//						return new PrintWriter(gzipOut) {
//							// we return a subclassed PrintWriter which finishes GZIPOutputStream when close is called
//							public void close() {
//								super.close();
//								try {
//									gzipOut.finish();
//								}
//								catch (IOException ie) {
//									System.err.println("Unexpected IOException when closing GZIPOutputStream");
//								}
//							}
//						};
//					}
//				};
//				response.setHeader("Content-Encoding", "gzip");
//			}
//		}
		
		String spec="", url="", testcode="", valOntology="0";
	spec=request.getParameter("spec");
	DasSpec dasSpec = DasSpec.SPEC1_53E;
	if(spec!=null){
		dasSpec = DasSpec.convertToRegistrySpecification(spec);	
	}
	
	
	url=request.getParameter("url")+url;
	testcode=request.getParameter("testcode");
	String []caps=request.getParameterValues("caps");
	DasCoordinateSystem coordinate=new DasCoordinateSystem();
	coordinate.setTestCode(testcode);
	DasCoordinateSystem[]coords={coordinate};
	if(caps==null){
		caps=Capabilities.getCapabilityStrings();
		}
	valOntology=request.getParameter("ontology")+valOntology;
	boolean validateOntology=false;
	if(valOntology.equals("on")){
		validateOntology=true;
	}
	Validator validator=new Validator();
	boolean updateDatabase=false;//false at the moment but we probably want this later( a server might have updated itself and want the registry to show new capabilities
	String auto_id=null; //null at the moment is got elsewhere
	
	Das1Source ds=new Das1Source();
//	try {
//		coords=registry.getCoordSysByName("Homo");
//	} catch (Exception e) {
//		// TODO Auto-generated catch block
//		e.printStackTrace();
//	}
	
	
	ds.setCapabilities(caps);

	ds.setCoordinateSystem(coords);
	ds.setUrl(url);
	//System.out.println("spec selecton="+spec+" "+url + " " + testcode + " " + caps +" "+auto_id+" ");
	DasValidationResult result=validator.validate(dasSpec, url,ds.getCapabilities(), coords, validateOntology, updateDatabase, registry, auto_id);
	//result.getError(cap)
	
	List<DasSource>sources=new ArrayList();
	sources.add(ds);
	ds.setValidCapabilities(result.getValidCaps());
	response.setContentType("text/html");//set the response type so it's shown in the browser!
	ServletResponseWriter writer = new RegistryServletResponseWriter();
	writer.writeResponse(response,sources,sources.size(), 0,0, false);
	

	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
	
	
	private void showXSLFile(HttpServletResponse resp) 
	throws IOException{
		//System.out.println("showing XSL file");
		resp.setContentType("text/xml");
		PrintWriter pw = resp.getWriter();
		InputStream is = getServletContext().getResourceAsStream(XSL_FILE);
		if (is != null) {
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			String line;
			while ((line = br.readLine()) != null) {
				//System.out.println(line);
				pw.println(line);
			}
		}
		pw.close();
		pw.flush();
	}
	
	private void welcomePage(HttpServletRequest req,
			HttpServletResponse resp)
	throws ServletException, IOException
	{
		resp.setContentType("text/html");
		PrintWriter pw = resp.getWriter();
		pw.println("<html>");
		pw.println("<head>");
		pw.println("<title>DAS Registry Server information</title>");
		pw.println("</head>");
		pw.println("<body>");
		pw.println("<h1>DAS Registry</h1>");
		pw.println("you might want to do a <a href=\"http://www.dasregistry.org/das1/sources\">sources</a> request");
		pw.println("</body>");
		pw.println("</html>");
		pw.close();
		pw.flush();
	}

}
